from os.path import join
import json

'''json文件根目录'''
basePath = r'./jsonFiles'
'''arr 字典数组 key 需要分组的属性'''


def groupByKey(arr, key):
    tempValue = arr[0][key]
    tempIndex = 0
    results = []
    while (True):
        tempArr = []
        flag = False
        for i, j in enumerate(arr[tempIndex:]):
            if j[key] == tempValue:
                tempArr.append(j)
            else:
                tempValue = j[key]
                tempIndex += i
                flag = True
                break
        results.append(tempArr)
        if not flag:
            break
    return results


'''生成md字符串'''


def generateMdText(content):
    data = json.loads(content)
    results = groupByKey(data, 'isCode')
    resultText = ''
    for i in results:
        if i[0]['isCode'] == True:
            text = joinCode(i)
            resultText += text
        else:
            text = joinText(i)
            resultText += text
    # 每一页结束插入md分隔符
    resultText += '\n---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n'
    return resultText


'''拼接普通文本'''


def joinText(arr):
    temp = ''
    for i in arr:
        temp += i['text'] + '\n'
    return temp


'''拼接代码文本'''


def joinCode(arr):
    # 拼接python md代码块开头
    result = '```python\n'
    temp = joinText(arr)
    # 替换掉文本中不符合python规范的单引号和双引号'''
    result += temp.replace('”', '\"').replace('“', '\"').replace('’', '\'')
    # 拼接python md代码块结尾
    result += '```\n'
    return result


# 页码范围18-565
for i in range(18, 41):
    p = join(basePath, str(i) + '.json')
    with open(p, 'r', encoding='utf-8') as f:
        # 读取对应的json文件
        content = f.read()
        # 生成md字符串
        mdText = generateMdText(content)
        with open('./md/test.md', 'a', encoding='utf-8') as f2:
            f2.write(mdText)
